package cn.tpshion.config;

import cn.tpshion.config.common.AssertUtil;
import cn.tpshion.config.service.AuthService;
import cn.tpshion.config.service.ZookeeperService;
import cn.tpshion.config.service.support.AuthInfo;
import cn.tpshion.config.service.support.AuthType;
import java.util.Objects;
import java.util.Properties;

/**
 * 配置处理工具类
 */
public class ConfigUtil {

    private static Properties properties = new Properties();

    private static ZookeeperService zookeeperService;

    /**
     * 初始化配置中心
     * @param host 配置中心地址
     * @param name 配置域
     * @param authInfo 认证信息
     */
    public static void init(String host, String name, AuthInfo authInfo){
        checkParam(host, name, authInfo);
        AuthService authService = new AuthService(host,authInfo);
        // 登录配置中心
        String token = authService.auth();
        // 获取配置中心zookeeper地址
        String configHost = authService.getConfigHost(token);
        // 初始化配置
        zookeeperService = new ZookeeperService(configHost,name,properties);
        zookeeperService.init();
    }

    /**
     * 关闭服务连接
     */
    public static void close(){
        if(Objects.nonNull(zookeeperService)){
            zookeeperService.close();
        }
    }

    /**
     * 检查参数
     * @param host
     * @param name
     * @param authInfo
     */
    public static void checkParam(String host, String name, AuthInfo authInfo){
        AssertUtil.notEmpty(host,"host配置中心地址不能为空");
        AssertUtil.notEmpty(name,"name配置域不能为空");
        AssertUtil.isTrue(Objects.nonNull(authInfo),"authInfo认证信息不能为空");
        AssertUtil.notEmpty(authInfo.getType(),"type认证类型不能为空");
        if(AuthType.PASSWORD.getType().equals(authInfo.getType())){
            AssertUtil.notEmpty(authInfo.getUsername(),"username用户名不能为空");
            AssertUtil.notEmpty(authInfo.getPassword(),"password密码不能为空");
        }
        if(AuthType.CODE.getType().equals(authInfo.getType())){
            AssertUtil.notEmpty(authInfo.getSecretkey(),"secretkey授权码不能为空");
        }
    }

    /**
     * 获取配置
     * @param key 配置名称
     * @param defaultValue 默认值
     * @return 返回配置内容
     */
    public static String getProperties(String key, String defaultValue){
        String property = properties.getProperty(key, defaultValue);
        return property;
    }

    /**
     * 获取配置
     * @param key 配置名称
     * @return
     */
    public static String getProperties(String key){
        return properties.getProperty(key);
    }

    public static Object getObject(String key){
        Object o = properties.get(key);
        if(Objects.isNull(o)){
            return o;
        }
        return o;
    }

    public static void main(String[] args) {
        AuthInfo authInfo = new AuthInfo();
        authInfo.setType(AuthType.CODE.getType());
        authInfo.setSecretkey("adsadada");
        init("localhost:8848","test",authInfo);
        while (true){

        }
    }
}
